package com.bkhc.product.service;

import com.bkhc.common.entity.Lookup;
import com.bkhc.common.enu.BrandStatusEnum;
import com.bkhc.common.permissions.bean.UserPermission;
import com.bkhc.common.repository.LookupRepository;
import com.bkhc.common.service.UserService;
import com.bkhc.common.util.CommonUtil;
import com.bkhc.common.util.response.PageUtil;
import com.bkhc.common.util.response.ResultCode;
import com.bkhc.common.util.response.ResultJson;
import com.bkhc.common.vo.UserBean;
import com.bkhc.product.entity.*;
import com.bkhc.product.repository.*;
import com.bkhc.product.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class BrandProductService {

    @Autowired
    private BrandProductRepository brandProductRepository;

    @Autowired
    private PriceRuleRepository priceRuleRepository;

    @Autowired
    private BrandGoodsRepository brandGoodsRepository;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private PriceService priceService;

    @Autowired
    private LookupRepository lookupRepository;

    @Autowired
    private BrandGoodPriceRepository brandGoodPriceRepository;

    @Autowired
    private BuessinesRepository buessinesRepository;

    @Autowired
    private BrandRepository brandRepository;

    @Autowired
    private PartnerRepository partnerRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private PartnerBrandRepository partnerBrandRepository;


    @Autowired
    private GoodspecRepository goodspecRepository;

    @Autowired
    private UserService userService;

    public ResultJson<?> getBrandProducts(BrandProduct brandProduct, int pageIndex, int pageSize){
        Sort.Order orders = new Sort.Order(Sort.Direction.DESC, "updateDate");
        PageRequest pageRequest = PageRequest.of(pageIndex-1, pageSize, Sort.by(orders));
        Page<BrandProduct> page = null;

        UserBean userBean = CommonUtil.getCrruentUser();
        if (userBean == null) return ResultJson.success();
        UserPermission userPermission = userService.queryUserPermission(userBean.getUserId());
        boolean isAdmin = userPermission.getRoles().stream().anyMatch(roleDetail -> "admin".equals(roleDetail.getRole_code()));
        Product product = new Product();
        if (!isAdmin) {
            String userId = userBean.getUserId();
            product.setPartnerId(userId);
            List<Product> productlist=productRepository.findAllByPartnerId(userId);
            List<String>  productCodeList = new ArrayList<>();
            for(Product p:productlist){
                productCodeList.add(p.getProductCode());
            }
            page =brandProductRepository.findByProductCodeIn(productCodeList,pageRequest);
        }else{
            if(brandProduct == null){
                page = brandProductRepository.findAll(pageRequest);
            }else {
                page = brandProductRepository.findAll(brandProduct, pageRequest);
            }
        }
        PageUtil pageUtil = new PageUtil(page);
        ResultJson<PageUtil> resultJson = ResultJson.success();
        resultJson.setData(pageUtil);
        return  resultJson;
    }


    public ResultJson<?> getBrandProductDetail(BrandProduct brandProduct) {
        BrandProductDetailVO brandProductDetail = brandProductRepository.findBrandProdectDetail(brandProduct.getProductCode(), brandProduct.getBrandCode());
        List<PriceRule> priceRules = priceRuleRepository.findByProductCodeAndBrandCode(brandProduct.getProductCode(), brandProduct.getBrandCode());
        if(!CollectionUtils.isEmpty(priceRules)){
            brandProductDetail.setRules(priceRules);
        }
        Partner p = partnerRepository.findByPartnerCode(brandProductDetail.getPartnerCode());
        brandProductDetail.setPartner(p);
        ResultJson<BrandProductDetailVO> resultJson = ResultJson.success();
        resultJson.setData(brandProductDetail);
        return resultJson;
    }

    public ResultJson<?> saveBrandProductPriceRule(List<PriceRule> priceRuleList) {
        if(!CollectionUtils.isEmpty(priceRuleList)){
            priceRuleRepository.deleteByProductCodeAndBrandCode(priceRuleList.get(0).getProductCode(),priceRuleList.get(0).getBrandCode());
            priceRuleRepository.saveAll(priceRuleList);
            BrandProduct bp = new BrandProduct();
            bp.setProductCode(priceRuleList.get(0).getProductCode());
            bp.setBrandCode(priceRuleList.get(0).getBrandCode());
            priceService.calculatePrice(bp);
        }

        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }

    public List<GoodsPriceVo> queryBrandProductPrice(String brandCode, String productCode) {
        UserBean user = CommonUtil.getCrruentUser();
        String indentity = "";
        if(user == null){
            List<Lookup> indentityList = lookupRepository.findByItemClass("Indentity");
            Lookup defaultIndentity = indentityList.stream().filter(x -> "default".equals(x.getAttr1())).findFirst().get();
            indentity = defaultIndentity.getItemCode();
        }else {
            try{
                System.out.println("用户id："+user.getUserId());
                Map map = buessinesRepository.getCustomerIndentity(user.getUserId());
                indentity = (String) map.get("identity");
            }catch (Exception e){
                System.out.println(e.getMessage());
                System.out.println("远程调用失败");
                List<Lookup> indentityList = lookupRepository.findByItemClass("Indentity");
                Lookup defaultIndentity = indentityList.stream().filter(x -> "default".equals(x.getAttr1())).findFirst().get();
                indentity = defaultIndentity.getItemCode();
            }
        }
        System.out.println("identify===>" +indentity);
        if (StringUtils.isEmpty(indentity)) {
            indentity = "market";
        }
        List<BrandGoodPrice> bgps = brandGoodPriceRepository.findByBrandCodeAndProductCodeAndIndentity(brandCode, productCode, indentity);
        Brand brand = brandRepository.findByBrandCode(brandCode);
        Product p = productRepository.findByProductCode(productCode);
        List<GoodsPriceVo> gpv = new ArrayList<>();

        if(!CollectionUtils.isEmpty(bgps)){
            for(BrandGoodPrice b:bgps){
                GoodsPriceVo vo = new GoodsPriceVo();
                vo.setBrandCode(brandCode);
                vo.setProductCode(productCode);
                vo.setProductName(p.getProductName());
                vo.setBrandName(brand.getBrandName());
                vo.setGoodsCode(b.getGoodsCode());
                List<GoodsSpec> goodspecList = goodspecRepository.findByGoodsCode(b.getGoodsCode());
                vo.setGoodsSpecList(goodspecList);
                List<BrandGoodPrice> bgpList = new ArrayList<>();
                bgpList.add(b);
                vo.setPriceList(bgpList);
                gpv.add(vo);
            }
        }

        return gpv;
    }

    public ResultJson<?> getBrandProductByBrandCode(String brandCode) {
        List<BrandProduct> brandProducts = brandProductRepository.findByBrandCode(brandCode);
        ResultJson<List<BrandProduct>> resultJson = ResultJson.success();
        resultJson.setData(brandProducts);
        return resultJson;
    }

    public List<BrandProductGoodDetail> getBrandProductList(String brandCode){
        Brand brand = brandRepository.findByBrandCode(brandCode);
        UserBean userBean = CommonUtil.getCrruentUser();
        UserPermission userPermission = userService.queryUserPermission(userBean.getUserId());
        boolean isAdmin = userPermission.getRoles().stream().anyMatch(roleDetail -> "admin".equals(roleDetail.getRole_code()));
        List<BrandProduct> brandProductList=null;
        if (isAdmin) {
            brandProductList = brandProductRepository.findByBrandCode(brandCode);
        }else {
            brandProductList = brandProductRepository.findByBrandCodeAndUser(brandCode,userBean.getUserId());
        }

        List<BrandProductGoodDetail> brandProductGoodDetailList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(brandProductList)){
            List<String> productCodes = new ArrayList<>();
            productCodes = brandProductList.stream().map(BrandProduct::getProductCode).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(productCodes)){
                List<Product> products = productRepository.findByProductCodeIn(productCodes);
                List<Goods> goodsListTem = goodsRepository.findByProductCodeIn(productCodes);
                List<String> goodsCode = goodsListTem.stream().map(Goods::getGoodsCode).collect(Collectors.toList());
                List<GoodsSpec> goodspcList = goodspecRepository.findByGoodsCodeIn(goodsCode);
                List<BrandGoods> brandGoodList = brandGoodsRepository.findByProductCodeIn(productCodes);
                for(BrandProduct bp:brandProductList){
                BrandProductGoodDetail brandProductGoodDetail=new BrandProductGoodDetail();
                brandProductGoodDetail.setBrandCode(brand.getBrandCode());
                brandProductGoodDetail.setBrandName(brand.getBrandName());
                Product producttem = products.stream().filter(product -> product.getProductCode().equals(bp.getProductCode())).findFirst().get();
                List<Goods> goodList = goodsListTem.stream().filter(x -> x.getProductCode().equals(bp.getProductCode())).collect(Collectors.toList());
                for(Goods g:goodList){
                    List<BrandGoods> tem = brandGoodList.stream().filter(x -> x.getGoodsCode().equals(g.getGoodsCode())).collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(tem)){
                        g.setChecked(true);
                    }else{
                        g.setChecked(false);
                    }
                    g.setGoodsSpec(goodspcList.stream().filter(x->x.getGoodsCode().equals(g.getGoodsCode())).collect(Collectors.toList()));
                }
                    PartnerBrand partnerBrand = partnerBrandRepository.findByBrandCodeAndProductCode(brand.getBrandCode(), producttem.getProductCode());
                if(partnerBrand!=null){
                    brandProductGoodDetail.setPartnerCode(partnerBrand.getPartnerCode());
                    brandProductGoodDetail.setPartnerName(partnerRepository.findByPartnerCode(partnerBrand.getPartnerCode()).getPartnerName());
                }
                brandProductGoodDetail.setGoodsList(goodList);
                brandProductGoodDetail.setProductName(producttem.getProductName());
                brandProductGoodDetail.setProductCode(producttem.getProductCode());
                brandProductGoodDetailList.add(brandProductGoodDetail);
                productCodes.add(bp.getProductCode());
            }
            }

        }
        return  brandProductGoodDetailList;
    }

    @Transactional
    public ResultJson<?> assignProductGoodforBrand(BrandProductItemVO itemVO) {
        UserBean userBean = CommonUtil.getCrruentUser();
        List<BrandProductGoodDetail> insert = itemVO.getInsert();
        List<BrandProductGoodDetail> delete = itemVO.getDelete();
        List<BrandProductGoodDetail> update = itemVO.getUpdate();
        if(!CollectionUtils.isEmpty(insert)){
            for(BrandProductGoodDetail detail:insert){
                BrandProduct old = brandProductRepository.findByProductCodeAndBrandCode(detail.getProductCode(), detail.getBrandCode());
                if(old!=null){
                    continue;
                }

                    detail.setBrandName(brandRepository.findByBrandCode(detail.getBrandCode()).getBrandName());


                    detail.setProductName(productRepository.findByProductCode(detail.getProductCode()).getProductName());

                BrandProduct bp = new BrandProduct();
                bp.setProductCode(detail.getProductCode());
                bp.setProductName(detail.getProductName());
                bp.setBrandCode(detail.getBrandCode());
                bp.setBrandName(detail.getBrandName());
                bp.setUpdator(userBean.getUserId());
                bp.setCreator(userBean.getUserId());
                brandProductRepository.save(bp);
                if(!StringUtils.isEmpty(detail.getPartnerCode())){
                    detail.setPartnerName(partnerRepository.findByPartnerCode(detail.getPartnerCode()).getPartnerName());
                    PartnerBrand pb = new PartnerBrand();
                    pb.setBrandCode(detail.getBrandCode());
                    pb.setBrandName(detail.getBrandName());
                    pb.setProductCode(detail.getProductCode());
                    pb.setProductName(detail.getProductName());
                    pb.setPartnerName(detail.getPartnerName());
                    pb.setPartnerCode(detail.getPartnerCode());
                    pb.setUpdator(userBean.getUserId());
                    pb.setCreator(userBean.getUserId());
                    partnerBrandRepository.save(pb);
                }
                List<Goods> goodsList = detail.getGoodsList();
                List<Goods> isCheckGoods = goodsList.stream().filter(x -> x.isChecked() == true).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(isCheckGoods)){
                    brandGoodsRepository.deleteByBrandCodeAndProductCode(detail.getBrandCode(), detail.getProductCode());
                    List<BrandGoods> bgs = new ArrayList<>();
                    for(Goods goods:isCheckGoods){
                        BrandGoods bgood = new BrandGoods();
                        bgood.setProductCode(detail.getProductCode());
                        bgood.setBrandCode(detail.getBrandCode());
                        bgood.setGoodsCode(goods.getGoodsCode());
                        bgood.setUpdator(userBean.getUserId());
                        bgood.setCreator(userBean.getUserId());
                        bgs.add(bgood);
                    }
                    brandGoodsRepository.saveAll(bgs);
                }
            }
        }
        if(!CollectionUtils.isEmpty(update)){
            for(BrandProductGoodDetail detail:update) {
                if(StringUtils.isEmpty(detail.getBrandName())){
                    detail.setBrandName(brandRepository.findByBrandCode(detail.getBrandCode()).getBrandName());
                }
                if(StringUtils.isEmpty(detail.getProductName())){
                    detail.setProductName(productRepository.findByProductCode(detail.getProductCode()).getProductName());
                }

                if(!StringUtils.isEmpty(detail.getPartnerCode())){
                    detail.setPartnerName(partnerRepository.findByPartnerCode(detail.getPartnerCode()).getPartnerName());
                    int i = partnerBrandRepository.deleteByBrandCodeAndProductCode(detail.getBrandCode(),detail.getProductCode());
                    PartnerBrand pb = new PartnerBrand();
                    pb.setBrandCode(detail.getBrandCode());
                    pb.setBrandName(detail.getBrandName());
                    pb.setProductCode(detail.getProductCode());
                    pb.setProductName(detail.getProductName());
                    pb.setPartnerName(detail.getPartnerName());
                    pb.setPartnerCode(detail.getPartnerCode());
                    pb.setUpdator(userBean.getUserId());
                    pb.setCreator(userBean.getUserId());
                    partnerBrandRepository.save(pb);
                }
                List<Goods> goodsList = detail.getGoodsList();
                List<Goods> isCheckGoods = goodsList.stream().filter(x -> x.isChecked() == true).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(isCheckGoods)){
                    brandGoodsRepository.deleteByBrandCodeAndProductCode(detail.getBrandCode(), detail.getProductCode());
                    List<BrandGoods> bgs = new ArrayList<>();
                    for(Goods goods:isCheckGoods){
                        BrandGoods bgood = new BrandGoods();
                        bgood.setProductCode(detail.getProductCode());
                        bgood.setBrandCode(detail.getBrandCode());
                        bgood.setGoodsCode(goods.getGoodsCode());
                        bgood.setUpdator(userBean.getUserId());
                        bgood.setCreator(userBean.getUserId());
                        bgs.add(bgood);
                    }
                    brandGoodsRepository.saveAll(bgs);
                }
            }
        }
        if(!CollectionUtils.isEmpty(delete)){
            for(BrandProductGoodDetail detail:delete) {
                brandProductRepository.deleteByBrandCodeAndProductCode(detail.getBrandCode(),detail.getProductCode());
                brandGoodsRepository.deleteByBrandCodeAndProductCode(detail.getBrandCode(),detail.getProductCode());
                partnerBrandRepository.deleteByBrandCodeAndProductCode(detail.getBrandCode(),detail.getProductCode());
            }
        }

        ResultJson resultJson = ResultJson.success();
        return resultJson;

    }

    public ResultJson<?> assignSupplier(PartnerBrand partnerBrand) {
        PartnerBrand partnerBrandTem = partnerBrandRepository.findByBrandCodeAndProductCode(partnerBrand.getBrandCode(), partnerBrand.getProductCode());
        if(partnerBrandTem == null){
            ResultJson resultJson = ResultJson.failure(ResultCode.ISEXIT_RESURCE);
            return resultJson;
        }
        partnerBrandRepository.save(partnerBrand);
        ResultJson resultJson = ResultJson.success();
        return resultJson;
    }

    public ResultJson<?> addBrandProduct(BrandProduct brandProduct) {
        BrandProduct b = brandProductRepository.findByProductCodeAndBrandCode(brandProduct.getProductCode(), brandProduct.getBrandCode());
        if(b!=null){
            ResultJson resultJson = ResultJson.failure(ResultCode.ISEXIT_RESURCE);
            return resultJson;
        }
        UserBean userBean = CommonUtil.getCrruentUser();
        brandProduct.setUpdator(userBean.getUserId());
        brandProduct.setCreator(userBean.getUserId());
        brandProduct.setBrandName(brandRepository.findByBrandCode(brandProduct.getBrandCode()).getBrandName());
        brandProduct.setProductName(productRepository.findByProductCode(brandProduct.getProductCode()).getProductName());
        brandProductRepository.save(brandProduct);
        ResultJson resultJson = ResultJson.success();
        return resultJson;
    }

    public ResultJson getBrandProductByPartner(String partnerCode, int pageIndex, int pageSize) {
        Sort.Order orders = new Sort.Order(Sort.Direction.DESC, "updateDate");
        PageRequest pageRequest = PageRequest.of(pageIndex-1, pageSize, Sort.by(orders));
        Page<PartnerBrand> page = null;
        PartnerBrand partnerBrand = new PartnerBrand();
        partnerBrand.setPartnerCode(partnerCode);
        page = partnerBrandRepository.findAll(partnerBrand, pageRequest);
        PageUtil pageUtil = new PageUtil(page);
        ResultJson<PageUtil> resultJson = ResultJson.success();
        resultJson.setData(pageUtil);
        return  resultJson;
    }

    public PartnerBrand getPartnerByBrandProduct(String productCode, String brandCode) {
        PartnerBrand partnerBrand = partnerBrandRepository.findByBrandCodeAndProductCode(brandCode, productCode);
        return partnerBrand;
    }

    public ResultJson<?> getBrandProductByBrandCodeAndPartnerCode(String brandCode, String partnerCode) {
        List<PartnerBrand> partnerBrands = partnerBrandRepository.findByBrandCodeAndPartnerCode(brandCode,partnerCode);
        ResultJson<List<PartnerBrand>> resultJson = ResultJson.success();
        resultJson.setData(partnerBrands);
        return resultJson;
    }
}
